package com.yunhai.store.service.impl;

import com.yunhai.common.dto.GlobalException;
import com.yunhai.model.entity.fms.FmsCodeDictEntity;
import com.yunhai.store.mapper.FmsCodeDictMapper;
import lombok.Synchronized;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class FmsCodeDictServiceImpl {

    @Resource
    private FmsCodeDictMapper fmsCodeDictMapper;


    public String getCanUseCode( int type ) throws Exception {
        FmsCodeDictEntity codeDict = fmsCodeDictMapper.selectById(type);
        if( codeDict == null ){
            throw GlobalException.gen(11000, "code不存在");
        }
        return genNewCode(codeDict.getLastCode());
    }


    public void updateById(Long type, String lastCode) throws Exception {
        FmsCodeDictEntity fmsCodeDictEntity = new FmsCodeDictEntity();
        fmsCodeDictEntity.setId(type);
        fmsCodeDictEntity.setLastCode(lastCode);
        fmsCodeDictMapper.updateById(fmsCodeDictEntity);
    }

    @Synchronized
    private String genNewCode( String lastCode ){
        int index = 0;
        for( int i=0; i<lastCode.length(); i++ ){
            char ch = lastCode.charAt(i);
            if( ch >= 48 && ch <= 57 ){
                index = i;
                break;
            }
        }
        String prefix = lastCode.substring(0, index);
        String intValueStr = lastCode.substring(index);
        intValueStr =  String.valueOf(Integer.valueOf(intValueStr)+1);
        int diff = 6- (prefix.length() + intValueStr.length());
        String fill = "";
        while ( diff-->0 ){
            fill = fill+ "0";
        }
        return prefix+fill+ intValueStr;
    }
}
